package com.zhenyu.test;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.JFrame;
import javax.swing.JPanel;
 
public class PaintPanel extends JPanel
{
    private static final long serialVersionUID = 1L;
    int x, y, x1, y1;
 
    public PaintPanel ( int startx, int starty )
    {
        super ();
        x = startx;
        y = starty;
        x1 = startx;
        y1 = starty;
        setBackground (Color.blue);
        addMouseMotionListener (new MouseAdapter ()
        {
            @Override
            public void mouseDragged ( MouseEvent e )
            {
                x = e.getX ();
                y = e.getY ();
                paintComponents (getGraphics ());
                x1 = x;
                y1 = y;
            }
 
            @Override
            public void mouseMoved ( MouseEvent e )
            {
                x1 = e.getX ();
                y1 = e.getY ();
            }
        });
    }
 
    @Override
    public void paintComponents ( Graphics g )
    {
        g.setColor (Color.BLACK);
        g.drawLine (x, y, x1, y1);
        g.dispose ();
    }
 
    public static void main ( String[] args )
    {
        JFrame jf = new JFrame ();
        final JPanel jp = new PaintPanel (0, 0);
        jf.add (jp);
        jf.setSize (300, 300);
        jf.setLocationRelativeTo (null);
        jf.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
        jf.setVisible (true);
    }
}